package pw.hais.znyj.mod.led;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.squareup.okhttp.Response;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import pw.hais.http.Http;
import pw.hais.http.base.OnHttpListener;
import pw.hais.sqlite.DBUtil;
import pw.hais.utils.L;
import pw.hais.znyj.R;
import pw.hais.znyj.base.app.BaseActivity;
import pw.hais.znyj.base.app.V;

/**
 * Created by hais1992 on 2016/11/20/020.
 */

public class LedActivity extends BaseActivity implements AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener {
    private ListView list_led;
    private LedAdapter ledAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_led_main);

        list_led = (ListView) findViewById(R.id.list_led);
        list_led.setOnItemClickListener(this);
        list_led.setOnItemLongClickListener(this);

        loadDataToView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadDataToView();
    }

    private void loadDataToView() {
        if (list_led != null) {
            List<LedModel> ledModelList = (List<LedModel>) DBUtil.findEntityList(LedModel.class, "", "");
            if (ledModelList != null) {
                ledAdapter = new LedAdapter(ledModelList);
                list_led.setAdapter(ledAdapter);
            }
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        L.showShort("指令已发送！");
        Map<String, String> data = new HashMap<>();
        data.put("shell", "sudo /root/hais/led " + ledAdapter.getItem(i).pin + " " + ledAdapter.getItem(i).time + " " + ledAdapter.getItem(i).number);
        Http.post(V.LOCALHOST + "/doShell.php", data, new OnHttpListener<String>() {
            @Override
            public void onSuccess(Response response, String data) {
                L.e("-------" + data);
            }
        });

    }

    @Override
    public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
        Intent intent = new Intent(context, LedEdieActivity.class);
        intent.putExtra(LedEdieActivity.INTENT_PIN_KEY, ledAdapter.getItem(i).id);
        startActivity(intent);
        return true;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_led_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_add) {
            startActivity(new Intent(this, LedEdieActivity.class));
        }
        return super.onOptionsItemSelected(item);
    }
}
